<template>
  <dys-modal
    :open="open"
    :title="t('接口管理')"
    @cancel="emit('cancel')"
    @ok="handleSubmit"
    :confirm-loading="loading"
    :width="400"
  >
    <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
      <a-form-item :label="t('学科名称')" v-bind="validateInfos.subjectName">
        <a-input
          v-model:value="modelRef.subjectName"
          :placeholder="t('请输入学科名称')"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item :label="t('学科编码')" v-bind="validateInfos.subjectCode">
        <a-input
          v-model:value="modelRef.subjectCode"
          :placeholder="t('请输入学科编码')"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item :label="t('学科图标')" v-bind="validateInfos.subjectIcon">
        <upload-file
          v-model:value="modelRef.subjectIcon"
          type="preview"
          accept="image/*"
          allow-clear
        ></upload-file>
      </a-form-item>
    </a-form>
  </dys-modal>
</template>
<script lang="ts" setup>
import { pick } from "lodash";
import { useI18n } from "vue-i18n";
import { reactive, ref, watch } from "vue";
import { Form, message } from "ant-design-vue";
import { add, update } from "@/api/answer/base-data/subject";
import type { FormRule } from "@/typing";
import type {
  SubjectParams,
  QueryResult,
} from "@/api/answer/base-data/subject/typing";
import UploadFile from "@/components/upload-file/index.vue";
interface Props {
  /**弹窗 */
  open: boolean;
  /**行数据 */
  model: QueryResult;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "ok"]);
const { t } = useI18n();
const initValue = (): SubjectParams => ({
  subjectId: null,
  subjectName: null,
  subjectCode: null,
  subjectIcon: null,
});
const modelRef = reactive(initValue());
const modelRule = reactive<FormRule<SubjectParams>>({
  subjectName: [{ required: true, message: () => t("请输入学科名称") }],
  subjectCode: [{ required: true, message: () => t("请输入学科编码") }],
  subjectIcon: [{ required: true, message: () => t("请上传学科图标") }],
});
const { validate, validateInfos, resetFields } = Form.useForm(
  modelRef,
  modelRule
);
watch([() => props.model, () => props.open], ([model]) => {
  resetFields(pick(model, Object.keys(modelRef)) || initValue());
});
const loading = ref(false);
/**提交 */
const handleSubmit = async () => {
  try {
    await validate();
  } catch {
    return message.warning(t("校验失败"));
  }
  loading.value = true;
  const { success } = await (props.model?.subjectId ? update : add)(modelRef);
  loading.value = false;
  if (success) {
    message.success(props.model?.subjectId ? t("修改成功") : t("新增成功"));
    emit("ok");
    emit("cancel");
  }
};
</script>
